import { loadEnv } from 'vite';
import type { ConfigEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
// import legacy from '@vitejs/plugin-legacy';
// @ts-ignore
import vueJsx from '@vitejs/plugin-vue-jsx';
import styleImport from 'vite-plugin-style-import';
import visualizer from 'rollup-plugin-visualizer';
import mdPlugin from 'vite-plugin-markdown';
import { viteMockServe } from 'vite-plugin-mock';

const path = require('path');
const gendoc = require('./bin/rollup-plugin-gendoc');

const CWD = process.cwd();

function configVisualizerConfig() {
  if (process.env.REPORT === 'true') {
    return visualizer({
      filename: './node_modules/.cache/visualizer/stats.html',
      template: 'treemap',
      open: true,
      gzipSize: true,
      brotliSize: true,
    }) as Plugin;
  }
  return [];
}

export default ({ mode, command }: ConfigEnv) => {
  // 环境变量
  const { VITE_BASE_URL } = loadEnv(mode, CWD);

  return {
    base: VITE_BASE_URL || '/',
    plugins: [
      gendoc(),
      mdPlugin({ mode: 'html' }),
      vue({ refTransform: true }),
      vueJsx(),
      styleImport({
        libs: [
          {
            libraryName: 'ant-design-vue',
            esModule: true,
            resolveStyle: (name) => {
              return `ant-design-vue/es/${name}/style/css`;
            },
          },
        ],
      }),
      configVisualizerConfig(),
      viteMockServe({
        ignore: /^_/,
        mockPath: 'mock',
        localEnabled: command === 'serve',
        logger: true,
      }),
    ],
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          modifyVars: {
            'primary-color': '#2265D1',
            'success-color': '#52A049',
            'heading-color': 'rgba(0, 0, 0, 1)',
          },
        },
        // scss: {
        //   additionalData: `
        //   @use 'sass:math';
        //   @import "src/styles/global.scss";
        //   `,
        // },
      },
    },
    resolve: {
      extensions: ['.js', '.json', '.ts', '.tsx', '.vue', 'md'],
      alias: {
        '@': path.resolve(__dirname, './src'),
        packages: path.resolve(__dirname, './packages'),
      },
    },
    build: {
      target: 'es2015',
      terserOptions: {
        compress: {
          keep_infinity: true,
          // Used to delete console in production environment
          drop_console: true,
        },
      },
      // Turning off brotliSize display can slightly reduce packaging time
      brotliSize: false,
      chunkSizeWarningLimit: 2000,
    },
    server: {
      host: true,
      port: 3001,
      // proxy: {
      //   '/api/': {
      //     target: 'http://spvr-test.ssc-hn.com',
      //     changeOrigin: true,
      //     ws: true,
      //   },
      // },
    },
    test: {
      // 启用类似 jest 的全局测试 API
      globals: true,
      // 使用 happy-dom 模拟 DOM
      // 这需要你安装 happy-dom 作为对等依赖（peer dependency）
      environment: 'happy-dom',
      transformMode: {
        web: [/.[tj]sx$/],
      },
    },
  };
};
